package com.simple.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dfe.common.exception.RRException;
import com.dfe.common.utils.Constant;
import com.dfe.modules.sys.dao.SysRoleDao;
import com.dfe.modules.sys.entity.SysRoleEntity;
import com.dfe.modules.sys.service.SysRoleMenuService;
import com.dfe.modules.sys.service.SysRoleService;
import com.dfe.modules.sys.service.SysUserRoleService;
import com.dfe.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色
 *
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	@Autowired
	private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;


	@Override
	public void saveOrUpdateRole(SysRoleEntity role) {
		saveOrUpdate(role);
		sysRoleMenuService.saveOrUpdate(role.getRoleId(),role.getMenuIdList());
	}

    @Override
    public void deleteBatch(List<Integer> roleIds) {
        //删除角色
        removeByIds(roleIds);

        //删除角色与菜单关联
        sysRoleMenuService.deleteByRoleIdList(roleIds);

        //删除角色与用户关联
        sysUserRoleService.deleteByRoleIdList(roleIds);
    }


    @Override
	public List<Integer> queryRoleIdList(Long createUserId) {
		return baseMapper.queryRoleIdList(createUserId);
	}

	@Override
	public List<SysRoleEntity> getListByRoleName(String roleName) {
		QueryWrapper<SysRoleEntity> qw = new QueryWrapper<SysRoleEntity>()
				.eq(roleName != null && !roleName.isEmpty(),"role_name",roleName);
		return list(qw);
	}


	/**
	 * 检查权限是否越权
	 */
	private void checkPrems(SysRoleEntity role){
		//如果不是超级管理员，则需要判断角色的权限是否超过自己的权限
		if(role.getCreateUserId() == Constant.SUPER_ADMIN){
			return ;
		}
		
		//查询用户所拥有的菜单列表
		List<Integer> menuIdList = sysUserService.queryAllMenuId(role.getCreateUserId());
		
		//判断是否越权
		if(!menuIdList.containsAll(role.getMenuIdList())){
			throw new RRException("新增角色的权限，已超出你的权限范围");
		}
	}
}
